<?php
require_once (__DIR__ . "/../conf/config.php");
require_once (__DIR__ . "/../funciones.php");
require_once('Tools.php');
class Producto {
        private $debug;
	public $id_cat;
	public $id_subcat;
	public $nombre;
	public $desc;
	public $cantidad = 0;
	public $precio = 0;
	public $categoria;
	public $subcategoria;
	public $aDefinition = array (
			"tabla" => "PRODUCTOS",
			"primary_key" => "COD_CATEGORIA, COD_SUBCATEGORIA",
			"nombre" => null,
			"descripcion" => null,
			"precio" => 0,
			"cantidad" => 0,
			"id_categoria" => null,
			"id_subcategoria" => null 
	);
	/**
	 * Constructor por defecto
	 * Si recibe las primary key del producto, muestra informacion asociada
	 * Si no recibe parametros se crea un producto nuevo
	 */
	public function __construct($primary_category = null, $primary_subcategory = null) {
		$this->debug = new Tools();
                if (isset ( $primary_category ) && isset ( $primary_subcategory )) {
			$this->id_cat = $primary_category;
			$this->id_subcat = $primary_subcategory;
                        $con = abrirConexion ();
			$sql = "SELECT *
                                FROM PRODUCTOS
                                WHERE `COD_CATEGORIA` = " . ( int ) $primary_category . " AND `COD_SUBCATEGORIA` = " . ( int ) $primary_subcategory;
                                // return $sql;
                                if ($res = mysqli_query ( $con, $sql )) {
                                    while ( $tupla = mysqli_fetch_array ( $res ) ) {
                                            $this->aDefinition ["precio"] = $tupla ['PRECIO'];
                                            $this->aDefinition ["descripcion"] = $tupla ['DESCRIPCION'];
                                            $this->aDefinition ["cantidad"] = $tupla ['UNIDADES_DISPONIBLES'];
                                            // $this->aDefinition["nombre"] =>
                                    }
                                    $this->aDefinition ["id_categoria"] = $primary_category;
                                    $this->aDefinition ["id_subcategoria"] = $primary_subcategory;
				cerrarConexion ( $con );
                                }
		}
	}
	/**
	 * devuelve el elemento de la matriz que se pasa por parametro
	 * 
	 * @param
	 *        	string
	 *        	return string
	 */
	public function __get($atributo) {
		if (isset ( $this->aDefinition [$atributo] )) {
			return $this->aDefinition [$atributo];
		} else {
			return false;
		}
	}
	
	/**
	 * establece un valor a la matriz
	 * atributos validos para posteriormente anadir un producto: nombre, descripcion, precio, cantidad, id_categoria, id_subcategoria
	 * 
	 * @param
	 *        	string elemento de la matriz
	 * @param
	 *        	valor que se asigna a la matriz
	 */
	public function __set($atributo, $valor) {
		if (isset ( $this->aDefinition [$atributo] )) {
			$this->aDefinition [$atributo] = $valor;
		}
	}
	/*
	 * Devuelve la matriz con todos los atributos return array
	 */
	public function getAllElements() {
		if (isset ( $this->id_cat ) && isset ( $this->id_subcat )) {
			$con = abrirConexion ();
			$sql = "SELECT *
                FROM PRODUCTOS
                WHERE `COD_CATEGORIA` = " . ( int ) $this->id_cat . " AND `COD_SUBCATEGORIA` = " . ( int ) $this->id_subcat;
			// return $sql;
			if ($res = mysqli_query ( $con, $sql )) {
				while ( $tupla = mysqli_fetch_array ( $res ) ) {
					$this->aDefinition ['id_categoria'] = $tupla ["COD_CATEGORIA"];
					$this->aDefinition ['id_subcategoria'] = $tupla ["COD_SUBCATEGORIA"];
					$this->aDefinition ["precio"] = $tupla ['PRECIO'];
					$this->aDefinition ["descripcion"] = $tupla ['DESCRIPCION'];
					$this->aDefinition ["cantidad"] = $tupla ['UNIDADES_DISPONIBLES'];
					// $this->aDefinition["nombre"] =>
				}
				cerrarConexion ( $con );
				return $this->aDefinition;
			} else {
				return "Error getAllElements Producto";
			}
		}
	}
	public function addProduct() {
		$con = abrirConexion ();
		$sql = "INSRT INTO PRODUCTOS
                VALUES `COD_CATEGORIA` = " . ( int ) $this->id_cat . " AND `COD_SUBCATEGORIA` = " . ( int ) $this->id_subcat;
		// return $sql;
		if ($res = mysqli_query ( $con, $sql )) {
			while ( $tupla = mysqli_fetch_array ( $res ) ) {
				$this->aDefinition ['id_categoria'] = $tupla ["COD_CATEGORIA"];
				$this->aDefinition ['id_subcategoria'] = $tupla ["COD_SUBCATEGORIA"];
				$this->aDefinition ["precio"] = $tupla ['PRECIO'];
				$this->aDefinition ["descripcion"] = $tupla ['DESCRIPCION'];
				$this->aDefinition ["cantidad"] = $tupla ['UNIDADES_DISPONIBLES'];
				// $this->aDefinition["nombre"] =>
			}
			cerrarConexion ( $con );
			return $this->aDefinition;
		} else {
			return "Error getAllElements Producto";
		}
	}
	public function reduceStock($quantity) {
		$con = abrirConexion ();
		$sql = 'UPDATE PRODUCTOS
                SET UNIDADES_DISPONIBLES = UNIDADES_DISPONIBLES -' . ( int ) $quantity . ' 
                WHERE COD_CATEGORIA = ' . $this->id_cat . ' AND COD_SUBCATEGORIA = ' . $this->id_subcat;
		if (! $res = mysqli_query ( $con, $sql )) {
			echo "Error reduceStock products.";
		}
		cerrarConexion ( $con );
	}
	public function checkStock() {
		if ($this->aDefinition ['cantidad'] > 0) {
			return true;
		}
		return false;
	}
        public function getProducts()
        {
            $con = abrirConexion ();
		$sql = 'SELECT * FROM `PRODUCTOS`';
		$products = array();
                if ($res = mysqli_query ( $con, $sql )) {
			while ( $tupla = mysqli_fetch_array ( $res, MYSQLI_ASSOC ) ) {
                            
                            $products[]= $tupla;
          		}
                        
		}else{echo "Error * products.";}
		cerrarConexion ( $con );
                return $products;
        }
        public function productosPaginados($comienzo, $cantidadRegistros)
        {
            $con = abrirConexion ();
		$sql = 'SELECT * FROM `PRODUCTOS` limit '. $comienzo.','.$cantidadRegistros;
		$products = array();
                if ($res = mysqli_query ( $con, $sql )) {
			while ( $tupla = mysqli_fetch_array ( $res, MYSQLI_ASSOC ) ) {
                            
                            $products[]= $tupla;
          		}
                        
		}else{echo "Error de paginacion products.";}
		cerrarConexion ( $con );
                return $products;
        }
}
?>